package com.topwalk.step01;

import lombok.extern.slf4j.Slf4j;

/**
 * ThreadLocalDemo
 *
 * @author tangfl
 */
@Slf4j
public class Demo5_7ThreadLocalDemo {

    static class ThreadA implements Runnable {

        private final ThreadLocal<String> threadLocal;

        public ThreadA(ThreadLocal<String> threadLocal) {
            this.threadLocal = threadLocal;
        }

        @Override
        public void run() {
            threadLocal.set("A");
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            log.info("ThreadA输出: {}", threadLocal.get());
        }
    }
    
    static class ThreadB implements Runnable {
        private final ThreadLocal<String> threadLocal;

        public ThreadB(ThreadLocal<String> threadLocal) {
            this.threadLocal = threadLocal;
        }

        @Override
        public void run() {
            threadLocal.set("B");
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            log.info("ThreadB输出：{}", threadLocal.get());
        }
    }

    public static void main(String[] args) {
        ThreadLocal<String> threadLocal = new ThreadLocal<>();
        new Thread(new ThreadA(threadLocal)).start();
        new Thread(new ThreadB(threadLocal)).start();
    }

}
